{% extends "base.html" %}

{% block title %}Trades{% endblock %}

{% block styles %}
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/css/fontawesome.min.css" rel="stylesheet">
<link href="/static/css/dataTables.bootstrap5.min.css" rel="stylesheet">
<link href="/static/css/buttons.bootstrap5.min.css" rel="stylesheet">
<link href="/static/css/trades-modern.css" rel="stylesheet">
{% endblock %}

{% block content %}
<div class="container-fluid px-2 px-md-4">
    <!-- 导航栏 -->
    <div class="side-navbar mb-3">
        <a class="navbar-brand" href="{{ url_for('index') }}">
            <i class="fas fa-chart-line"></i> Trading Analyzer
        </a>
        <a class="nav-link" href="{{ url_for('trades') }}">
            <i class="fas fa-list"></i> Trades
        </a>
        <a class="nav-link" href="{{ url_for('statistics_page') }}">
            <i class="fas fa-chart-bar"></i> Statistics
        </a>
    </div>
    
    <div class="trades-card">
        <div class="row mb-3 align-items-center">
            <div class="col">
                <h2 class="fw-bold" style="letter-spacing:-1px;">Trades</h2>
            </div>
            <div class="col-auto">
                <div class="btn-group">
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#columnSettingsModal">
                        <i class="fas fa-cog"></i> Column Settings
                    </button>
                    <button type="button" class="btn btn-success" id="exportCsv">
                        <i class="fas fa-file-export"></i> Export CSV
                    </button>
                    <button type="button" class="btn btn-info" id="importCsvBtn">
                        <i class="fas fa-file-import"></i> 导入CSV
                    </button>
                    <input type="file" id="importCsvInput" accept=".csv" style="display:none;">
                </div>
            </div>
        </div>

        <!-- Column Settings Modal -->
        <div class="modal fade" id="columnSettingsModal" tabindex="-1" aria-labelledby="columnSettingsModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="columnSettingsModalLabel">Column Settings</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6>Basic Information</h6>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="序号" id="col-序号" checked>
                                    <label class="form-check-label" for="col-序号">序号</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="品种" id="col-品种" checked>
                                    <label class="form-check-label" for="col-品种">品种</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="开仓时间" id="col-开仓时间" checked>
                                    <label class="form-check-label" for="col-开仓时间">开仓时间</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="平仓时间" id="col-平仓时间" checked>
                                    <label class="form-check-label" for="col-平仓时间">平仓时间</label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h6>Price & Quantity</h6>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="开仓价格" id="col-开仓价格" checked>
                                    <label class="form-check-label" for="col-开仓价格">开仓价格</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="开数" id="col-开数" checked>
                                    <label class="form-check-label" for="col-开数">开数</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="平仓价格" id="col-平仓价格" checked>
                                    <label class="form-check-label" for="col-平仓价格">平仓价格</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="平数" id="col-平数" checked>
                                    <label class="form-check-label" for="col-平数">平数</label>
                                </div>
                            </div>
                        </div>
                        <hr>
                        <div class="row">
                            <div class="col-md-6">
                                <h6>Trade Details</h6>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="方向" id="col-方向" checked>
                                    <label class="form-check-label" for="col-方向">方向</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="开仓类型" id="col-开仓类型" checked>
                                    <label class="form-check-label" for="col-开仓类型">开仓类型</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="平仓类型" id="col-平仓类型" checked>
                                    <label class="form-check-label" for="col-平仓类型">平仓类型</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="交易类型" id="col-交易类型" checked>
                                    <label class="form-check-label" for="col-交易类型">交易类型</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="开仓侧" id="col-开仓侧" checked>
                                    <label class="form-check-label" for="col-开仓侧">开仓侧</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="持仓时间" id="col-持仓时间" checked>
                                    <label class="form-check-label" for="col-持仓时间">持仓时间</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="第几笔" id="col-第几笔" checked>
                                    <label class="form-check-label" for="col-第几笔">第几笔</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="交易时段" id="col-交易时段" checked>
                                    <label class="form-check-label" for="col-交易时段">交易时段</label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h6>Profit & Loss</h6>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="单手点数" id="col-单手点数" checked>
                                    <label class="form-check-label" for="col-单手点数">单手点数</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="总点数" id="col-总点数" checked>
                                    <label class="form-check-label" for="col-总点数">总点数</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="毛利润" id="col-毛利润" checked>
                                    <label class="form-check-label" for="col-毛利润">毛利润</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="净利润" id="col-净利润" checked>
                                    <label class="form-check-label" for="col-净利润">净利润</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="佣金" id="col-佣金" checked>
                                    <label class="form-check-label" for="col-佣金">佣金</label>
                                </div>
                            </div>
                        </div>
                        <hr>
                        <div class="row">
                            <div class="col-md-6">
                                <h6>Floating P/L</h6>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="最大浮盈点" id="col-最大浮盈点" checked>
                                    <label class="form-check-label" for="col-最大浮盈点">最大浮盈点</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="最大浮盈$" id="col-最大浮盈$" checked>
                                    <label class="form-check-label" for="col-最大浮盈$">最大浮盈$</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="最大浮亏点" id="col-最大浮亏点" checked>
                                    <label class="form-check-label" for="col-最大浮亏点">最大浮亏点</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="最大浮亏$" id="col-最大浮亏$" checked>
                                    <label class="form-check-label" for="col-最大浮亏$">最大浮亏$</label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h6>Trade Analysis</h6>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="入场理由" id="col-入场理由" checked>
                                    <label class="form-check-label" for="col-入场理由">入场理由</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="离场理由" id="col-离场理由" checked>
                                    <label class="form-check-label" for="col-离场理由">离场理由</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="止损点位" id="col-止损点位" checked>
                                    <label class="form-check-label" for="col-止损点位">止损点位</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="止损理由" id="col-止损理由" checked>
                                    <label class="form-check-label" for="col-止损理由">止损理由</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="止盈点位" id="col-止盈点位" checked>
                                    <label class="form-check-label" for="col-止盈点位">止盈点位</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="止盈理由" id="col-止盈理由" checked>
                                    <label class="form-check-label" for="col-止盈理由">止盈理由</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="打分" id="col-打分" checked>
                                    <label class="form-check-label" for="col-打分">打分</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="评价" id="col-评价" checked>
                                    <label class="form-check-label" for="col-评价">评价</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="OR" id="col-OR" checked>
                                    <label class="form-check-label" for="col-OR">OR</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="CR" id="col-CR" checked>
                                    <label class="form-check-label" for="col-CR">CR</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="FWR" id="col-FWR" checked>
                                    <label class="form-check-label" for="col-FWR">FWR</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input column-toggle" type="checkbox" value="操作" id="col-操作" checked>
                                    <label class="form-check-label" for="col-操作">操作</label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary" id="saveColumnSettings">Save changes</button>
                    </div>
                </div>
            </div>
        </div>

        <div style="width: 100%;">
            <!--table id="tradesTable" class="table table-striped table-hover table-bordered align-middle" style="width: 100%;"-->
            <table id="tradesTable" class="table table-hover table-bordered align-middle" style="width: 100%;">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>品种</th>
                        <th>开仓时间</th>
                        <th>开仓价格</th>
                        <th>开数</th>
                        <th>平仓时间</th>
                        <th>平仓价格</th>
                        <th>平数</th>
                        <th>方向</th>
                        <th>开仓类型</th>
                        <th>平仓类型</th>
                        <th>交易类型</th>
                        <th>开仓侧</th>
                        <th>单手点数</th>
                        <th>总点数</th>
                        <th>毛利润</th>
                        <th>净利润</th>
                        <th>佣金</th>
                        <th>持仓时间</th>
                        <th>第几笔</th>
                        <th>交易时段</th>
                        <th>最大浮盈点</th>
                        <th>最大浮盈$</th>
                        <th>最大浮亏点</th>
                        <th>最大浮亏$</th>
                        <th>入场理由</th>
                        <th>离场理由</th>
                        <th>止损点位</th>
                        <th>止损理由</th>
                        <th>止盈点位</th>
                        <th>止盈理由</th>
                        <th>打分</th>
                        <th>评价</th>
                        <th>OR</th>
                        <th>CR</th>
                        <th>FWR</th>
                        <th>实际风险</th>
                        <th>后续最大盈利</th>
                        <th>潜在盈亏比</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for trade in trades %}
                    {% set net_profit_str = trade.net_profit|replace('$', '')|replace(',', '') %}
                    {% set net_profit = net_profit_str|float %}
                    {% set profit_class = '' %}
                    {% if net_profit >= 500 %}
                        {% set profit_class = 'profit-large' %}
                    {% elif net_profit >= 50 %}
                        {% set profit_class = 'profit-medium' %}
                    {% elif net_profit > -50 and net_profit < 50 %}
                        {% set profit_class = 'profit-micro' if net_profit >= 0 else 'loss-micro' %}
                    {% elif net_profit <= -250 %}
                        {% set profit_class = 'loss-large' %}
                    {% elif net_profit <= -50 %}
                        {% set profit_class = 'loss-medium' %}
                    {% endif %}
                    <tr data-trade-id="{{ trade.trade_id }}" class="{{ profit_class }}">
                        <td>{{ trade.index }}</td>
                        <td data-field="symbol">{{ trade.symbol }}</td>
                        <td>{{ trade.open_datetime.split('+')[0][2:10].replace('-', '') + ' ' + trade.open_datetime.split('+')[0][11:16] if '+' in trade.open_datetime else trade.open_datetime[2:10].replace('-', '') + ' ' + trade.open_datetime[11:16] }}</td>
                        <td class="editable" data-field="open_price">{{ '%.2f' % trade.open_price if trade.open_price is not none else '' }}</td>
                        <td class="editable" data-field="open_qty">{{ trade.open_qty if trade.open_qty is not none else '' }}</td>
                        <td>{{ trade.close_datetime.split('+')[0][2:10].replace('-', '') + ' ' + trade.close_datetime.split('+')[0][11:16] if '+' in trade.close_datetime else trade.close_datetime[2:10].replace('-', '') + ' ' + trade.close_datetime[11:16] }}</td>
                        <td class="editable" data-field="close_price">{{ '%.2f' % trade.close_price if trade.close_price is not none else '' }}</td>
                        <td class="editable" data-field="close_qty">{{ trade.close_qty if trade.close_qty is not none else '' }}</td>
                        <td>{{ trade.direction }}</td>
                        <td>{{ trade.open_order_type }}</td>
                        <td class="editable-select" data-field="close_order_type">{{ '' if not trade.close_order_type or trade.close_order_type|lower == 'nan' else trade.close_order_type }}</td>
                        <td class="editable-select" data-field="trade_type">{{ '' if not trade.trade_type or trade.trade_type|lower == 'nan' else trade.trade_type }}</td>
                        <td class="editable-select" data-field="side">{{ '' if not trade.side or trade.side|lower == 'nan' else trade.side }}</td>
                        <td>{{ '%.2f' % trade.point_profit_per_lot if trade.point_profit_per_lot is not none else '' }}</td>
                        <td>{{ '%.2f' % trade.total_points if trade.total_points is not none else '' }}</td>
                        <td>{{ '%.2f' % trade.gross_profit if trade.gross_profit is not none else '' }}</td>
                        <td>{{ '%.2f' % trade.net_profit if trade.net_profit is not none else '' }}</td>
                        <td>{{ '%.2f' % trade.commission if trade.commission is not none else '' }}</td>
                        <td>{{ trade.holding_time }}</td>
                        <td>{{ trade.nth_trade }}</td>
                        <td>{{ trade.session }}</td>
                        <td class="editable" data-field="max_floating_profit_points">{{ (('%.2f' % trade.max_floating_profit_points) if trade.max_floating_profit_points is not none and trade.max_floating_profit_points|string != '' and trade.max_floating_profit_points|lower != 'nan' else '') }}</td>
                        <td class="editable" data-field="max_floating_profit_dollars">{{ (('%.2f' % trade.max_floating_profit_dollars) if trade.max_floating_profit_dollars is not none and trade.max_floating_profit_dollars|string != '' and trade.max_floating_profit_dollars|lower != 'nan' else '') }}</td>
                        <td class="editable" data-field="max_floating_loss_points">{{ (('%.2f' % trade.max_floating_loss_points) if trade.max_floating_loss_points is not none and trade.max_floating_loss_points|string != '' and trade.max_floating_loss_points|lower != 'nan' else '') }}</td>
                        <td class="editable" data-field="max_floating_loss_dollars">{{ (('%.2f' % trade.max_floating_loss_dollars) if trade.max_floating_loss_dollars is not none and trade.max_floating_loss_dollars|string != '' and trade.max_floating_loss_dollars|lower != 'nan' else '') }}</td>
                        <td class="editable-select" data-field="entry_reason">{{ '' if not trade.entry_reason or trade.entry_reason|lower == 'nan' else trade.entry_reason }}</td>
                        <td class="editable-select" data-field="exit_reason">{{ '' if not trade.exit_reason or trade.exit_reason|lower == 'nan' else trade.exit_reason }}</td>
                        <td class="editable" data-field="stop_loss_price">{{ ('%.2f' % trade.stop_loss_price) if trade.stop_loss_price is not none and trade.stop_loss_price|string != '' and trade.stop_loss_price|lower != 'nan' else '' }}</td>
                        <td class="editable-select" data-field="stop_loss_reason">{{ '' if not trade.stop_loss_reason or trade.stop_loss_reason|lower == 'nan' else trade.stop_loss_reason }}</td>
                        <td class="editable" data-field="take_profit_price">{{ ('%.2f' % trade.take_profit_price) if trade.take_profit_price is not none and trade.take_profit_price|string != '' and trade.take_profit_price|lower != 'nan' else '' }}</td>
                        <td class="editable-select" data-field="take_profit_reason">{{ '' if not trade.take_profit_reason or trade.take_profit_reason|lower == 'nan' else trade.take_profit_reason }}</td>
                        <td class="editable-select" data-field="rating">{{ '' if not trade.rating or trade.rating|lower == 'nan' else trade.rating }}</td>
                        <td class="editable" data-field="evaluation">{{ '' if not trade.evaluation or trade.evaluation|lower == 'nan' else trade.evaluation }}</td>
                        <td class="computed-field" data-field="open_rrr">{{ ('%.2f' % trade.open_rrr) if trade.open_rrr is not none and trade.open_rrr|string != '' and trade.open_rrr|lower != 'nan' else '' }}</td>
                        <td class="computed-field" data-field="close_rrr">{{ ('%.2f' % trade.close_rrr) if trade.close_rrr is not none and trade.close_rrr|string != '' and trade.close_rrr|lower != 'nan' else '' }}</td>
                        <td class="computed-field" data-field="fwr">{{ ('%.2f' % trade.fwr) if trade.fwr is not none and trade.fwr|string != '' and trade.fwr|lower != 'nan' else '' }}</td>
                        <td class="computed-field" data-field="actual_risk">{{ ('%.2f' % trade.actual_risk) if trade.actual_risk is not none and trade.actual_risk|string != '' and trade.actual_risk|lower != 'nan' else '' }}</td>
                        <td class="editable" data-field="extend">{{ ('%.2f' % trade.extend) if trade.extend is not none and trade.extend|string != '' and trade.extend|lower != 'nan' else '' }}</td>
                        <td class="computed-field" data-field="prr">{{ ('%.2f' % trade.prr) if trade.prr is not none and trade.prr|string != '' and trade.prr|lower != 'nan' else '' }}</td>
                        <td>
                            <button class="btn btn-link text-danger p-0 delete-trade" title="删除">
                                <i class="fas fa-trash-alt"></i>
                            </button>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="/static/js/jquery.min.js"></script>
<script src="/static/js/bootstrap.bundle.min.js"></script>
<script src="/static/js/jquery.dataTables.min.js"></script>
<script src="/static/js/dataTables.bootstrap5.min.js"></script>
<script src="/static/js/dataTables.buttons.min.js"></script>
<script src="/static/js/buttons.bootstrap5.min.js"></script>
<script src="/static/js/buttons.html5.min.js"></script>
<script src="/static/js/trades-modern.js"></script>
<script>
$('#importCsvBtn').click(function() {
    $('#importCsvInput').val('').click();
});
$('#importCsvInput').change(function() {
    var file = this.files[0];
    if (!file) return;
    var formData = new FormData();
    formData.append('file', file);
    $.ajax({
        url: '/import_orders',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(res) {
            var message = '';
            
           // 显示错误信息（如果有的话）
           if (!res.success && res.error_messages && res.error_messages.length > 0) {
                message += '\n❌ 错误详情:\n';
                res.error_messages.forEach(function(error) {
                    message += '• ' + error + '\n';
                });
            } else if (!res.success && res.error) {
                message += '\n❌ 错误: ' + res.error + '\n';
            }

            // 始终显示成功消息（如果有的话）
            if (res.success_message) {
                if (res.success) {
                    message += '✅ ' + res.success_message + '\n\n';
                } else {
                    message += '⚠️ 部分成功: ' + res.success_message + '\n\n';
                }
            }
            
            // 始终显示详细统计
            message += '📊 详细统计:\n';
            message += '• 新交易数: ' + res.new_trades + '\n';
            message += '• 重复订单数: ' + res.duplicate_orders + '\n';
            message += '• 重复交易数: ' + res.duplicate_trades + '\n';
            
            // 始终显示订单保存详情（如果有的话）
            if (res.save_orders_result) {
                message += '• 保存的新订单: ' + res.save_orders_result.saved_count + '\n';
                message += '• 跳过的重复订单: ' + res.save_orders_result.duplicate_count + '\n';
            }
            
            // 始终显示警告信息（如果有的话）
            if (res.warning_messages && res.warning_messages.length > 0) {
                message += '\n⚠️ 警告信息:\n';
                res.warning_messages.forEach(function(warning) {
                    message += '• ' + warning + '\n';
                });
            }
            
            alert(message);
            location.reload();
        },
        error: function(xhr) {
            var res = {};
            try { res = JSON.parse(xhr.responseText); } catch(e) {}
            
            var message = '';

            // 显示错误信息
            message += '❌ 导入出错\n\n';
            if (res.error_messages && res.error_messages.length > 0) {
                message += '错误详情:\n';
                res.error_messages.forEach(function(error) {
                    message += '• ' + error + '\n';
                });
            } else {
                message += '错误: ' + (res.error || xhr.responseText || '网络错误');
            }

            // 如果有部分成功信息，也要显示
            if (res.success_message) {
                message += '⚠️ 部分成功: ' + res.success_message + '\n\n';
            }
            
            // 显示详细统计（如果有的话）
            if (res.new_trades !== undefined || res.duplicate_orders !== undefined) {
                message += '📊 详细统计:\n';
                if (res.new_trades !== undefined) message += '• 新交易数: ' + res.new_trades + '\n';
                if (res.duplicate_orders !== undefined) message += '• 重复订单数: ' + res.duplicate_orders + '\n';
                if (res.duplicate_trades !== undefined) message += '• 重复交易数: ' + res.duplicate_trades + '\n';
                
                if (res.save_orders_result) {
                    message += '• 保存的新订单: ' + res.save_orders_result.saved_count + '\n';
                    message += '• 跳过的重复订单: ' + res.save_orders_result.duplicate_count + '\n';
                }
                message += '\n';
            }
            
            // 显示警告信息（如果有的话）
            if (res.warning_messages && res.warning_messages.length > 0) {
                message += '⚠️ 警告信息:\n';
                res.warning_messages.forEach(function(warning) {
                    message += '• ' + warning + '\n';
                });
                message += '\n';
            }
            
            alert(message);
        }
    });
});
</script>
{% endblock %}